﻿var hHeightBottom = 0;
var bReload = false;
var nAnpha = 31;
var nReportType = 1;
var fromdate = "";
var todate = "";
var toutDisplayControl = 0;
var sTime = " 00:00:00";
var eTime = " 23:59:59";
if (typeof ReportTracking == 'undefined')
    ReportTracking = {};

ReportTracking.Core = {
    Init: {
        Resize: function () {
            clearInterval(timeintarval);
            //$('#main').layout('collapse', 'west');
            $(function () {
                $("#main").css({ 'width': $(window).width() - 1, 'height': $(window).height() - $('#divbottom').height() });
                $('#main').layout();
                $('#main').layout('panel', 'west').panel({
                    onCollapse: function () {
                        $("#main").css({ 'width': $(window).width() - 1, 'height': $(window).height() - $('#divbottom').height() });
                        $('#main').layout();
                        $('#container .datagrid-wrap').addClass('fixGridInChrom');
                    },
                    onExpand: function () {
                        $("#main").css({ 'width': $(window).width() - 1, 'height': $(window).height() - $('#divbottom').height() });
                        $('#main').layout();
                        $('#container .datagrid-wrap').addClass('fixGridInChrom');
                    }

                });

            });
            //ReportTracking.Core.Utility.AutoResizeColumnGrid('tbPL2', 1000);
            var timeintarval = setInterval("$('#tbPL2').datagrid('fitColumns')", 1000);
            ReportTracking.Core.Processor.ResizeDataGrid('container', 'west');
        },
        Onload: function () {
            ReportTracking.Core.Init.Resize();
            $('#container .datagrid-wrap').addClass('fixGridInChrom');
            //Admin.Core.Init.LoadConter();
            ReportTracking.Core.Interface.SelectecMenu();
        },
        InitDate: function () {
            var d = new Date();
            var day = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
            fromdate = day + ' 00:00:00';
            todate = day + ' 23:59:59';
        }
    },
    Browser: {
        setCookie: function (c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        },
        getCookie: function (c_name) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        },
        getUrlVars: function () {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
    },
    Processor: {
        ResizeDataGrid: function (hcontainer, wcontainer)//hcontainer : tab div chua grid, wcontainer: lay vi tri offset cho grid
        {
            var h = $('#' + hcontainer).height();
            var w = $('#' + wcontainer).width();
            $('#' + hcontainer + ' .datagrid-wrap').height(h); // set lai chieu cao cho gridview
            $('#' + hcontainer + '.datagrid-pager').offset({ top: $(window).height() - hHeightBottom, left: w }); //set vi tri cho paging
        },
        LoadDataForPL2: function () {
            var fd = $('#sDay').datebox('getValue');
            var td = $('#eDay').datebox('getValue');
            var speed = $('#txtSpeed').val();
            var arrId = ReportTracking.Core.Processor.GetValueCombobox('cbDVKD');
            var nResult = ReportTracking.Core.Utility.CheckDay(fd, td, nAnpha);
            if (nResult == 1) {
                $.messager.alert('Thông báo!', 'Vui lòng chọn lại thời gian không quá ' + nAnpha + ' ngày!', 'info');
                return;
            }
            else if (nResult == -1) {
                $.messager.alert('Thông báo!', 'Thời gian bắt đầu không được lớn hơn thời gian kết thúc!', 'info');
                return;
            }
            $('#tbPL2').datagrid('loadData', { "total": 0, "rows": [] });
            bReload = false;
            ReportTracking.Core.Browser.setCookie('bRequest', 0, 1);
            $('#tbPL2').datagrid({
                url: 'Services/PL2.ashx',
                queryParams: { 'fromday': fd, 'today': td, 'speed': speed, 'dvkd': arrId, 'reporttype': 1 },
                onLoadSuccess: function () {
                    if (!bReload) {
                        setTimeout(function () {
                            ReportTracking.Core.Browser.setCookie('bRequest', 1, 1);
                            bReload = true;
                        }, 2000);
                    }

                    ReportTracking.Core.Processor.ResizeDataGrid('container', 'west');
                }
            });

        },
        GetValueCombobox: function (cbName) {
            var s = $('#' + cbName).combotree('getValues');
            var arrID = '';
            var j = 0;
            for (i = 0; i < s.length; i++) {
                if (s[i] != '-1') {
                    arrID += s[i] + '-';
                    j++;
                }
            }
            return arrID;
        },
        //Tam thoi get Text dung LINQ de loc chua co ham loc theo ID 
        GetTextCombobox: function (cbName) {
            var s = $('#' + cbName).combotree('getText');
            return s;


        },
        ClearAndAddTab: function (divName) {
            $(function () {
                $('#' + divName).html('');
                var arrHTML = new Array();
                arrHTML[arrHTML.length] = "<table id='list'>";
                arrHTML[arrHTML.length] = "</table>";
                arrHTML[arrHTML.length] = "<div id='pager'>";
                arrHTML[arrHTML.length] = "</div>";
                $('#' + divName).html(arrHTML.join(''));
                $('#result').html('');
            });


        },
        ResizeGrid: function (gridName) {
            var nHpage = $('#pg_pager').height();
            var nTbTable = $('.ui-jqgrid-hbox').height();
            var nHeight = $(window).height() - ($('#hd').height() + nHpage + nTbTable) - 3;
            var nWidth = $(window).width() - wDelte;
            jQuery('#' + gridName).jqGrid('setGridHeight', nHeight);
            jQuery('#' + gridName).jqGrid('setGridWidth', nWidth);
        },
        GetResult: function (data) {
            $('#result').html('');
            $('#result').show();
            var obj = JSON.parse(data);
            if (obj != undefined) {
                var strHTML = new Array();
                var sDv = 'Đơn vị kinh doanh vận tải: ';
                switch (obj.Info.Type) {
                    case 1:
                        {
                            strHTML[strHTML.length] = '<b class="resultStyle1">Thống kê vi phạm về tốc độ xe chạy:';
                            $('#divbtnReport').show();
                            break;
                        }
                    case 2:
                        {
                            strHTML[strHTML.length] = '<b class="resultStyle1">Thống kê vi phạm về hành trình chạy xe:';
                            break;
                        }

                    case 3:
                        {
                            strHTML[strHTML.length] = '<b class="resultStyle1">Thống kê vi phạm về số lần và thời gian dừng đỗ:';
                            $('#divbtnReport').show();
                            break;
                        }
                    case 4:
                        {
                            strHTML[strHTML.length] = '<b class="resultStyle1">Thống kê vi phạm về đóng, mở cửa xe:';
                            $('#divbtnReport').show();
                            break;
                        }

                    case 5:
                        {
                            strHTML[strHTML.length] = '<b class="resultStyle1">Thống kê vi phạm về thời gian lái xe:';
                            $('#divbtnReport').show();
                            break;
                        }
                    case 6:
                        {
                            $('#divbtnReport').hide();
                            strHTML[strHTML.length] = '<b class="resultStyle1">Tổng hợp tình hình vi phạm các tiêu chí:';
                            break;
                        }
                    case 7:
                        {
                            $('#divbtnReport').hide();
                            sDv = 'Đơn vị vận tải: ';
                            strHTML[strHTML.length] = '<b class="resultStyle1">Tổng hợp tình hình vi phạm các tiêu chí(theo địa phương):';

                            break;
                        }
                    case 8:
                        {
                            $('#divbtnReport').hide();
                            sDv = 'Đơn vị vận tải: ';
                            strHTML[strHTML.length] = '<b class="resultStyle1">Tổng hợp tình hình vi phạm theo loại hình hoạt động:';
                            break;
                        }
                    case 9:
                        {
                            sDv = 'Đơn vị vận tải: ';
                            strHTML[strHTML.length] = '<b class="resultStyle1">Tổng hợp tình hình vi phạm theo từng Sở GTVT:';
                            $('#divbtnReport').hide();
                            break;
                        }
                    case 10:
                        {

                            strHTML[strHTML.length] = '<b class="resultStyle1">Tổng hợp tình hình vi phạm toàn quốc:';
                            break;
                        }

                    default:
                        $('#divbtnReport').hide();
                        strHTML[strHTML.length] = '<b>';
                        break;

                }
                strHTML[strHTML.length] = ' từ: ';
                strHTML[strHTML.length] = obj.Info.fd;
                strHTML[strHTML.length] = ' đến: ';
                strHTML[strHTML.length] = obj.Info.td;
                strHTML[strHTML.length] = '. Tổng số lượng xe vi phạm: ';
                strHTML[strHTML.length] = obj.Info.total;
                strHTML[strHTML.length] = '.</b>';
                strHTML[strHTML.length] = '</br>';
                strHTML[strHTML.length] = '<b style="color:#0066cc; font:bold 16px Arial;">';
                strHTML[strHTML.length] = sDv;
                strHTML[strHTML.length] = obj.Info.DVKD;
                strHTML[strHTML.length] = '</b>';
                $('#result').html(strHTML.join(' '));
            }

        },
        ExportData: function () {
            $('#loading').show();
            var date = new Date();
            var sFolder = date.getMonth() + 1 + '' + date.getDate() + '' + date.getFullYear();
            var url = 'Services/Report/PL2.ashx';
            switch (nReportType) {
                case 1: url = 'Services/Report/PL2.ashx';
                    break;
                case 2:
                    url = 'Services/Report/PL3.ashx';
                    break;
                case 3:
                    url = 'Services/Report/PL4.ashx';
                    break;
                case 4:
                    url = 'Services/Report/PL5.ashx';
                    break;
                case 5:
                    url = 'Services/Report/PL6.ashx';
                    break;
                case 6:
                    url = 'Services/Report/PL7.ashx';
                    break;
                case 7:
                    url = 'Services/Report/PL8.ashx';
                    break;
                case 8:
                    url = 'Services/Report/PL9.ashx';
                    break;
                case 9:
                    url = 'Services/Report/PL10.ashx';
                    break;
                case 10:
                    url = 'Services/Report/PL11.ashx';
                    break;
                default:
                    break;

            }
            $.ajax({
                type: "post",
                url: url,
                error: function (returnval) {
                    
                    $('#loading').hide();
                    $.messager.alert('Thông báo!', 'Export Excel bị lỗi!', 'error');
                },
                success: function (data) {
                    $('#loading').hide();
                    window.location.href = 'FileExcel/' + sFolder + '/' + data + '.xlsx';
                }
            });
            /*$.post(url, function (data, status) {
            $('#loading').hide();
            window.location.href = 'FileExcel/' + sFolder + '/' + data + '.xlsx';

            });*/

        },

        LogOut: function () {

            ReportTracking.Core.Browser.setCookie('Logout', '', 1);
            $.ajax({
                'type': 'POST',
                'url': 'ServiceTracking.asmx/LogOut',
                dataType: "json",
                //data: { 'param': session, id: id.id },
                async: true,
                success: function (msg) {
                    if (msg.result == true) {

                        window.location.href = 'Login.aspx?ReturnUrl=Index.aspx';
                    }
                }
            });
            window.location.href = 'Login.aspx?ReturnUrl=Index.aspx';
        },
        Login: function () {
            var username = $('#txtUserName').val();
            var password = $('#txtPassword').val();
            var url = location.hostname;
            $.ajax({
                'type': 'POST',
                //'url': 'Service/Login.ashx',
                url: 'ServiceTracking.asmx/Login',
                data: { 'User': username, 'Pass': password, 'Url': url },
                dataType: "json",
                async: true,
                success: function (msg) {
                    try {
                        if (msg.result == true) {
                            ReportTracking.Core.Browser.setCookie('Logout', username, 1);
                            window.location.href = 'Index.aspx';

                        }
                        else {

                            $('#info').html('Người dùng hoặc mã số không đúng!');
                            $('#txtUserName').val('');
                            $('#txtPassword').val('');
                            $('#txtUserName').focus();
                            return;
                        }
                    }
                    catch (e) {

                        // window.location.href = 'Default.aspx';
                    }

                }
                /*error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#info').html('Người dùng hoặc mã số không đúng!');
                return;
                }*/
            });
        },
        OnKeyPressLogin: function (event) {
            if (event.keyCode == 13) {
                ReportTracking.Core.Processor.Login();
            }
            else {

                return;
            }

        },
        GetDVGTVT: function () {
            var fd = $('#sDay').datebox('getValue') + sTime;
            var td = $('#eDay').datebox('getValue') + eTime;
            $('#cbDVKD').combotree({
                url: 'Services/CbDVKDVT.ashx?fd=' + fd + '&td=' + td

            });
        },
        CloseTooltip: function (tooltipName) {
            $('#' + tooltipName).tooltip('hide');
        },
        OpenWindow: function (type, url, div, title, width, height, mode, coll, min, max, closed, resize, drag, icon, idchild) {

            if (type == 1) {

                $('#' + div).window({ //window
                    href: url,
                    title: title,
                    width: width,
                    height: height,
                    modal: mode,
                    collapsible: coll,
                    minimizable: min,
                    maximizable: max,
                    closable: close,
                    resizable: resize,
                    draggable: drag,
                    cache: true,
                    iconCls: icon,
                    zIndex: 500,
                    onClose: function () {
                        //$('#quanlyspeed').window('destroy',true);
                        $('#quanlyspeed').css('display', 'none');
                    },
                    onLoad: function () {

                    },
                    onMaximize: function () {
                        switch (idchild) {
                            case 1:
                                {

                                    break;
                                }
                        }
                    },
                    onRestore: function () {
                        switch (idchild) {
                            case 1:
                                {

                                    break;
                                }
                        }
                    }

                });
            }
            else if (type == 2) { //dialog

                $('#' + div).dialog({
                    href: url,
                    title: title,
                    width: width,
                    height: height,
                    modal: mode,
                    collapsible: coll,
                    minimizable: min,
                    maximizable: max,
                    closable: close,
                    resizable: resize,
                    draggable: drag,
                    cache: true,
                    iconCls: icon,
                    zIndex: 500,
                    onClose: function () {
                        clearInterval(toutDisplayControl);

                    },
                    onOpen: function () {
                        toutDisplayControl = setInterval(function () {
                            $('#editmodtbspeed').css('z-index', 99999);
                            $('#delmodtbspeed').css('z-index', 99999);
                            $('#alertmod_tbspeed').css('z-index', 99999);
                        }, 700);
                    }
                });
            }

        },
        CloseWindow: function (type, div) {

            type == 1 ? $('#' + div).window('close') : $('#' + div).dialog('close');
            // type == 1 ? $('#' + div).window('destroy') : $('#' + div).dialog('destroy');

        },
        OpenWindowSpeed: function () {
            ReportTracking.Core.Processor.OpenWindow(2, "DefinedSpeed.aspx", "quanlyspeed1", "Quản lý tốc độ của phương tiện", 450, 300, false, false, false, false, true, false, true, 'icon-setting', 12);
        },
        OpenWindowChart: function () {
            ReportTracking.Core.Processor.OpenWindow(1, "Chart/index.htm", "quanlyspeed", "Thống kê loại hình dịch vụ dạng biểu đồ", 650, 460, false, false, false, false, true, false, true, 'icon-setting', 12);
        },
        GetHeightResult: function () {
            var s = ReportTracking.Core.Processor.GetTextCombobox('cbDVKD');
            var arrSplit = new Array();
            if (s.length > 0) {
                arrSplit = s.split(',');
                if (arrSplit.length > 0) {
                    if (arrSplit[0] == 'All') {
                        return hResult;
                    }
                    if (arrSplit.length > nNumberDVKD) {
                        var nLoop = arrSplit.length / nNumberDVKD;
                        var hRs = 0;
                        for (var i = 0; i < nLoop; i++) {
                            hRs += hResult;
                        }
                        return hRs;
                    }
                }
            }

            return hResult;
        },
        CallReportTracking: function () {

            var param = ReportTracking.Core.Browser.getUrlVars();
            var trp = parseInt(param['t'], 10);
            var fdrp = param['fd'];
            var tdrp = param['td'];
            var dvkd = param['dvkd'];
            switch (trp) {
                case 1:
                    {

                        CreateGridPL2('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 2:
                    {
                        CreateGridPL3('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 3:
                    {
                        CreateGridPL4('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 4:
                    {
                        CreateGridPL5('list', fdrp, tdrp, dvkd);
                        break;

                    }
                case 5:
                    {
                        CreateGridPL6('list', fdrp, tdrp, dvkd);
                        break;

                    }
                case 6:
                    {
                        CreateGridPL7('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 7:
                    {
                        CreateGridPL8('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 8:
                    {
                        CreateGridPL9('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 9:
                    {
                        CreateGridPL10('list', fdrp, tdrp, dvkd);
                        break;
                    }
                case 10:
                    {
                        CreateGridPL11('list', fdrp, tdrp);
                        break;
                    }


                default:
                    break;

            }
        }

    },

    Ajax: {
        CallServer: function (pUrl, pData, pFuncNameSuccess, pType, pAsync, pdataType, pcontenType) {
            pType = pType;
            pAsync = pAsync;
            $.ajax({
                url: pUrl,
                async: pAsync,
                cache: false,
                type: pType,
                data: pData,
                contentType: pcontenType,
                dataType: pdataType,
                success: pFuncNameSuccess,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // window.location.href = 'Login.aspx';
                    $.messager.alert('Thông báo!', errorThrown, 'error');
                    return;
                }
            });
        },
        CallServerLoadControl: function (serviceURL, control, page, container, title) {

            $('#loading').show();
            ReportTracking.Core.Processor.ClearAndAddTab('detail');
            var _data = "{ controlLocation: '" + control + "', Para: { id: '123',name:'thinhdaica', page:'" + page + "'} }";
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: serviceURL, //'ScriptService.asmx/GetControlHtml',
                data: _data,
                dataType: "json",
                success: function (msg) {
                    /* if (title.length > 0) {
                    $('#container').panel('setTitle', title);
                    }*/
                    var _msg = msg.d;
                    if (_msg) {
                        //$('#' + container).html(_msg.replace('name="__VIEWSTATE" id="__VIEWSTATE"', 'id="cuibap" '));
                        $('#' + container).html(_msg);
                    }
                    //ReportTracking.Core.Init.Resize();
                    $('#loading').hide();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!");
                }
            });
        }
    },
    Gridview:
    {
        PhuLuc2: function () {
            $(function () {
                $('#tbPL2').datagrid({
                    method: 'get',
                    singleSelect: true,
                    pagination: true,
                    nowrap: true,
                    fitColumns: true,
                    showPageList: false,
                    pageSize: 20,
                    pageList: [20, 30, 40],
                    rownumbers: true
                });
            });
        }
    },
    Utility:
     {
         AutoResizeColumnGrid: function (tbName, delay) {
             var timeintarval = setInterval("$('#" + tbName + "').datagrid('fitColumns')", delay);

         },
         CheckDay: function (date1, date2, anpha) {
             var fd = new Date(date1);
             var td = new Date(date2);
             var nDay = (td - fd) / (3600 * 1000 * 24);
             if (nDay >= 0) {
                 if (nDay <= anpha) {
                     return 0;

                 }
                 else
                     return 1;
             }
             else {
                 return -1;
             }

         }

     },
    Interface: {
        SelectecMenu: function () {
            $('.MenuLeftTool li').click(function () {
                $('.MenuLeftTool li a').removeClass();
                $(this).children().addClass('selected');
            });
        },
        SelectedMenuText: function () {
            $('.menu-text a').click(function () {
                $('.menu-text a').removeClass();
                $(this).addClass('selected');

            });
        }
    }
},
ReportTracking.Core.Browser.setCookie('bRequest', 0, 1);